#!/bin/bash

function info() {
echo Usage: `basename $0` [pmtdn] cmd args
exit 2
}

while getopts  ":p:t:m:d:n:F" opt; do
	case $opt in
	p) cpu=$OPTARG;;
	m) mem=$OPTARG;;
	t) max_task=$OPTARG;;
	d) job_id=$OPTARG;;
	n) name=$OPTARG;;
	F) ;;
	?) info;;
	esac
done
shift $(($OPTIND - 1))

# echo $@

if [ $# -lt 1 ]; then info; fi

# . $var

if test -z "$max_task"; then max_task=20; fi
if test -z "$name"; then name=tes; fi
if test -z "$cpu"; then cpu=4; fi
if test -z "$mem"; then mem=4; fi

wait_time=60

while true; do
	if test $(qstat -f -u `whoami`|grep Job_Owner|wc -l) -lt $max_task; then
		sleep 2
		if test -n "$job_id"; then
			id_next=$(sub -d$job_id -p$cpu -m$mem -n$name $@)
 
			if test -n "$id_next"; then
				# echo sub with dependency $job_id
				echo $id_next
			else
				sub -p$cpu -m$mem -n$name $@
				# echo sub without dependency
			fi
		else
			sub -p$cpu -m$mem -n$name $@
			# echo sub without dependency
		fi
		
		break
	else
		sleep $wait_time
	fi
done

# . $cmd_done